<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="searchData" layout="inline">
            <a-form-item label="排三角名称" v-if="permissionStore.hasPermisson('typsj.cx')">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="searchData.name"
                @press-enter="huiche" />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :style="{ zIndex: 999 }"
      :ok-loading="pageData.pageLoading" :mask-closable="false" placement="bottom" popup-container=".main-base-style"
      :visible="pageData.showAdd" height="100%" unmountOnClose @ok="sideOk" @cancel="addCancel">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <div style="width: 1400px; overflow: auto" class="scrollbar">
          <el-scrollbar>
            <a-form ref="formRef" layout="inline" :model="dataForm">
              <a-form-item label="名称" field="atName" :rules="[{ required: true, message: '名称必填' }]"
                :validate-trigger="['change', 'blur']">
                <a-input class="bacClass" v-model="dataForm.atName"></a-input>
              </a-form-item>

              <a-form-item label="机型" field="models" :rules="[{ required: true, message: '机型必填' }]"
                :validate-trigger="['change', 'blur']">
                <a-select popup-container="html" :style="{ width: '150px' }" class="bacClass" v-model="dataForm.models">
                  <a-option value="单面机">单面机</a-option>
                  <a-option value="双面机">双面机</a-option>
                </a-select>
              </a-form-item>
              <a-form-item>
                <a-radio-group v-model="tagValue">
                  <a-radio v-for="item in tags" :value="item.id">
                    {{ item.val }}
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-form>
            <label style="padding-right: 38px; position: relative; top: -25px; left: 14px">备注</label>
            <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" style="width: 632px"
              allow-clear show-word-limit />
            <div style="height: 20px"></div>
            <a-space>
              <a-input-number class="bacClass"  :class="{'opcity-ipt':addFlag == 2}" :min="1" :max="999" size="mini" v-model="numb.col" :disabled="addFlag == 2"></a-input-number>
              <a-button size="mini" :type="addFlag == 2 ? '' : 'primary'" :status="addFlag == 2 ? '' : 'success'"
                @click="addCol" :disabled="addFlag == 2">
                设置路数
              </a-button>
              <a-button size="mini" :type="addFlag == 1 ? '' : 'primary'" :status="addFlag == 1 ? '' : 'success'"
                @click="setLoop" :disabled="addFlag == 1">
                设置循环
              </a-button>
            </a-space>

            <div v-for="(item, index) in sjdata.sj as any"
              style="text-align: center; margin: 20px auto; width: 100%; overflow-x: auto">
              <div style="text-align: left">
                {{ item.type }}
              </div>

              <div class="thead">
                <div class="th" style="width: 50px">序号</div>
                <div class="th" style="width: 250px">用针</div>
                <div class="th" style="width: 30px" v-for="i2 in item.typeData[0].needleList" :key="i2.way">
                  {{ i2.way }}
                </div>
              </div>
              <div class="tbody" v-for="i1 in item.typeData" :key="i1">
                <div class="td" style="width: 50px">{{ i1.serialNumber }}</div>
                <div class="td" style="width: 250px">
                  <!-- <a-input class="bacClass" v-model="i1.needleName"></a-input>888 -->
                  <a-select popup-container="html" class="bacClass" @click="psjpblistSelect('')"
                    @search="psjpblistSelect" placeholder="" allow-search allow-clear :style="{ width: '230px' }"
                    v-model="i1.needleName">
                    <a-option v-for="item in psjpblist" :value="item.materialName">{{ item.materialName }}
                    </a-option>
                  </a-select>
                </div>
                <div class="td" style="height: 34px; width: 30px; vertical-align: middle; border: 1px solid gray"
                  v-for="i2 in i1.needleList" :key="i2">
                  <div style="width: 100%; height: 100%" class="gesture" @click="setSJValue(i2, item)">{{
        tags.filter((o) => o.id === i2.needle)[0]?.val
      }}
                  </div>
                </div>
              </div>
              <div style="height: 20px"></div>
              <a-space fill>
                <a-input-number class="bacClass" :min="1" :max="999" v-model="numb.row[index]"
                  size="mini"></a-input-number>
                <a-button @click="addRow(item)" type="primary" size="mini">设置用针</a-button>
              </a-space>

              <div style="height: 20px"></div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </a-drawer>
    <a-modal :width="1200" v-model:visible="settingLoopVisible" :on-before-ok
="settingLoopOK" @cancel="settingLoopVisible = false" :mask-closable="false"
      draggable>
      <template #title>
        设置循环
      </template>
      <div>
        <div class="flex mb-5">
          <a-button class="mr-3" type="outline" status="success" @click="loopAdd">新增</a-button>
          <a-button type="outline" status="danger" @click="loopDel">删除</a-button>
        </div>
        <div class="w-full">
          <a-table :columns="settingLoopColumns" :data="TempSettingLoopData" v-model:selectedKeys="settingLoopKeys"
            row-key="serialNumber" :row-selection="settingLoopCheckBox" :pagination="false">
            <template #wayEnd="{ record }">
              <a-input-number v-model="record.wayEnd" :min="record.wayStart" @change="wayEndChange" />
            </template>
            <template #loopCount="{ record }">
              <a-input-number v-model="record.loopCount" :min="1" @change="loopCountChange" />
            </template>
          </a-table>
        </div>
      </div>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs, watch } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal, Scrollbar } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'

import { localeText } from '@/api/aggridZw'
import usePermission from '@/store/modules/permission'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import _ from 'lodash'

interface Firm {
  name: string
  id: number
}

interface PSJ {
  atName: string
  models: string
  id: number | string
  remark: string
  firm: string
  atCode: string
  arrangement: string
  deleteState: string | number
  obsoleteState: string | number
  createName: string
  createTime: string
  updateName: string
  updateTime: string
}

const tags = [
  { id: '1', val: '̶' },
  { id: '2', val: 'Ո' },
  { id: '3', val: 'Ս' },
  { id: '4', val: 'Ʌ' },
  { id: '5', val: 'V' },
]
export default {
  name: 'PSJList',
  setup() {
    //查询
    let cxbl = ''
    const selectHandler = () => {
      page.value = 1
      cxbl = searchData.name
      doRefresh()
    }
    const setLoop = () => {
      TempSettingLoopData.value = []
      TempSettingLoopData.value  =  _.cloneDeep(settingLoopData.value)
      settingLoopVisible.value = true

    }
    const addFlag = ref(0) //0 为未选择  1 为设置路数 2为设置循环
    const settingLoopOK = () => {
     let isNull =  TempSettingLoopData.value.some(item=>item.wayEnd==null||item.wayEnd==null)
      if (isNull) {
        Message.warning('请先填写再保存！')
        return false
      }
      settingLoopData.value = _.cloneDeep(TempSettingLoopData.value )
      sjdata.sj.forEach((o: any) => {
        o.typeData.forEach((o1: any, id: number) => {
          o1.needleList = []
          settingLoopData.value.forEach((item) => {
            for (let index = item.wayStart; index < item.wayEnd + 1; index++) {

              o1.needleList.push({
                way: index,
                needle: '',
              })

            }
          })
        })
      })
      addFlag.value = 2
      TempSettingLoopData.value  = []
      settingLoopVisible.value = false
      return  true
    }
    const wayEndChange = () => {
      countLoopBetween()
    }
    const loopCountChange = () => {
      countLoopBetween()
    }
    //循环设置删除
    const loopDel = () => {
      TempSettingLoopData.value =
        TempSettingLoopData.value.filter(item => !settingLoopKeys.value.includes(item.serialNumber))
      settingLoopKeys.value = []
      // const delKeys = settingLoopKeys.value.filter(item=>item.selected)
    }
    //循环设置新增
    const loopAdd = () => {
      if (TempSettingLoopData.value.length == 0||TempSettingLoopData.value.every(item => item.serialNumber != 1)) {
        TempSettingLoopData.value.unshift({
          serialNumber: 1,
          wayStart: 1,
          wayEnd: null,
          loopCount: null,
          loopBetween: ""
        },)
        return
      }
      if (TempSettingLoopData.value.some(item => item.loopBetween === undefined || item.loopBetween === '')) {
        Message.warning('请先填写再添加！')
        return
      }
      let obj: any = {
        serialNumber: 1,
        wayStart: 1,
      }
      let maxSerialNumber = Math.max(...TempSettingLoopData.value.map(item => item.serialNumber))
      if (maxSerialNumber != TempSettingLoopData.value.length) {
        // for (const index in TempSettingLoopData.value) {
        //   console.log(TempSettingLoopData.value[index].serialNumber);

        //   if (TempSettingLoopData.value[index].serialNumber + 1 !== TempSettingLoopData.value[index + 1].serialNumber) {
        //     obj.serialNumber = TempSettingLoopData.value[index].serialNumber + 1
        //     obj.wayStart = parseInt(TempSettingLoopData.value[index].loopBetween.split('~')[1]) + 1
        //     TempSettingLoopData.value.push(obj)
        //     TempSettingLoopData.value.sort((a,b)=>a.serialNumber-b.serialNumber)
        //     return
        //   }
        // }
        for (let i = 1; i <= maxSerialNumber + 1; i++) {
          if (!TempSettingLoopData.value.some(item => item.serialNumber === i)) {
            obj.serialNumber = i
            obj.wayStart = parseInt(TempSettingLoopData.value[i - 2].loopBetween.split('~')[1]) + 1

            break;
          }
        }


      } else {
        let lastObj: any = TempSettingLoopData.value.find(item => item.serialNumber === maxSerialNumber)
        obj.serialNumber = maxSerialNumber + 1
        obj.wayStart = parseInt(lastObj.loopBetween.split('~')[1]) + 1

      }

      TempSettingLoopData.value.push(obj)
      TempSettingLoopData.value.sort((a, b) => a.serialNumber - b.serialNumber)
    }
    //计算循环区间
    const countLoopBetween = () => {
      TempSettingLoopData.value.forEach((item, index) => {
        if (item.wayEnd && item.loopCount) {
          TempSettingLoopData.value[index].loopBetween = item.wayStart + '~' + ((item.wayEnd - item.wayStart + 1) * item.loopCount + item.wayStart - 1)
          if (TempSettingLoopData.value[index + 1]) {
            TempSettingLoopData.value[index + 1].wayStart = (item.wayEnd - item.wayStart + 1) * item.loopCount + item.wayStart
            if (TempSettingLoopData.value[index + 1].wayEnd < (item.wayEnd - item.wayStart + 1) * item.loopCount + item.wayStart) {
              TempSettingLoopData.value[index + 1].wayEnd = (item.wayEnd - item.wayStart + 1) * item.loopCount + item.wayStart + 1
            }
          }
        }
      })
    }
    const table1Ref = ref<any>(null)
    const tableColumns = [
      {
        title: '序号',
        key: 'atCode',
        dataIndex: 'atCode',
        width: 150,
      },
      {
        title: '名称',
        key: 'atName',
        dataIndex: 'atName',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },

      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      // {
      //     title: "删除状态",
      //     key: "deleteState",
      //     dataIndex: "deleteState",
      //     width: 100,
      //     slotName: "deleteState",
      //     fixed: 'right'
      // },
      {
        title: '操作',
        key: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right',
      },
    ]
    const settingLoopColumns = [
      {
        title: '序号',
        key: 'serialNumber',
        dataIndex: 'serialNumber',
        width: 80,
      },
      {
        title: '路数开始',
        key: 'wayStart',
        dataIndex: 'wayStart',
        width: 100,
      },
      {
        title: '路数结束',
        key: 'wayEnd',
        dataIndex: 'wayEnd',
        width: 100,
        slotName: 'wayEnd'
      },

      {
        title: '循环次数',
        key: 'loopCount',
        dataIndex: 'loopCount',
        width: 80,
        slotName: 'loopCount'
      },
      {
        title: '循环期间',
        key: 'loopBetween',
        dataIndex: 'loopBetween',
        width: 120,
      },
    ]
    const settingLoopKeys: any = ref([])
    const settingLoopCheckBox = reactive({
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    });
    const settingLoopData:any = ref([
    ])
    const TempSettingLoopData:any = ref([
    ])
    let tc: any[] = tableColumns.map((o: any) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = 250
      if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 90
        obj['cellRenderer'] = {
          template: `
            <a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const b = props.params.data.deleteState

            const a = () => {
              editHandler(props.params.data)
            }

            return {
              a,
              e: pageData.isEdit,
            }
          },
        }
      }

      return obj
    })
    tc.unshift({
      showRowGroup: 'hide_def',
      headerName: "",
      "checkboxSelection": true,
      "headerCheckboxSelection": true,
      "pinned": "left",
      "width": 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: "left",
    })
    let configTable1 = {
      url: 'product/arrangementTriangle/getPage', //接口路径
      queryData: {
        //接口参数
        deleteState: 0,
        atName: cxbl,
      },
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tc,
      fileName: 'PSJList-1'
    }

    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    const settingLoopVisible = ref(false)
    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }

    function change1(val: any) {
      size.value = val
      doRefresh()
    }

    const headerShow = ref<boolean>(true)

    const selChange = (v: any) => {
      post({
        url: 'product/arrangementTriangle/getAtName',
        data: {
          key: v,
          deleteState: 0,
        },
      }).then((res1: any) => {
        if (res1.code === 200) {
          pageData.gcList = res1.data
        }
      })
    }

    function doRefresh() {
      table1Ref.value.setQuery({
        deleteState: 0,
        atName: cxbl,
      })
    }

    // 子表修改数据请求
    function addsonlist() {
      post({
        url: '/product/arrangementTriangle/insert',
        data: {
          id: 2,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)
            pagination.setTotalSize(data.total)
          }
        })
        .catch(console.log)
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const pageData = reactive<{
      gcList: Firm[]
      showAdd: boolean
      pageLoading: boolean
      sideTitle: string
      rHeight: number | undefined
      btnList: any[]
      isEdit: boolean
    }>({
      gcList: [],
      rHeight: 0,
      showAdd: false,
      pageLoading: false,
      sideTitle: '新增排三角资料',
      btnList: [],
      isEdit: false,
    })

    onMounted(() => {
      // 切换tap到本页面执行的方法
      emitter.on('PSJList', () => {
        // selCxAll({});
        doRefresh()
      })
    })
    const queryData = reactive({
      firm: '',
      clothType: '',
    })
    const addHandler = () => {
      dataForm.models = '双面机'
      addFlag.value = 0
      numb.col = 1
      numb.row = [2, 4]

      sjdata.sj = [
        {
          type: '上盘',
          typeData: [
            {
              serialNumber: 1,
              needleName: '',
              needleList: [
                {
                  needle: '',
                  way: 1,
                },
              ],
            },
            {
              serialNumber: 2,
              needleName: '',
              needleList: [
                {
                  needle: '',
                  way: 1,
                },
              ],
            },
          ],
        },
        {
          type: '下盘',
          typeData: [
            {
              serialNumber: 1,
              needleName: '',
              needleList: [{ way: 1 }],
            },
            {
              serialNumber: 2,
              needleName: '',
              needleList: [
                {
                  needle: '',
                  way: 1,
                },
              ],
            },
            {
              serialNumber: 3,
              needleName: '',
              needleList: [
                {
                  needle: '',
                  way: 1,
                },
              ],
            },
            {
              serialNumber: 4,
              needleName: '',
              needleList: [
                {
                  needle: '',
                  way: 1,
                },
              ],
            },
          ],
        },
      ]
      settingLoopData.value = []
      pageData.showAdd = true
      pageData.sideTitle = '新增排三角资料'
    }
    const numb = reactive<{ row: number[]; col: number }>({
      row: [1, 1],
      col: 1,
    })
    const addCol = () => {
      // 最大列数

      let maxColNumber = 0
      addFlag.value = 1
      sjdata.sj[0].typeData[0].needleList.forEach((o: any) => {
        if (o.way > maxColNumber) {
          maxColNumber = parseInt(o.way)
        }
      })
      let n = maxColNumber - numb.col
      if (n < 0) {
        for (let i = n; i < 0; i++) {
          sjdata.sj.forEach((o: any) => {
            o.typeData.forEach((o1: any, id: number) => {
              o1.needleList.push({
                way: maxColNumber + Math.abs(n - i) + 1,
                needle: '',
              })
            })
          })
        }
      } else if (n > 0) {
        for (let i = 0; i < n; i++) {
          sjdata.sj.forEach((o: any, i: number) => {
            o.typeData.forEach((o1: any) => {
              o1.needleList.pop()
            })
          })
        }
      } else {
        return
      }
    }

    const subCol = () => {
      if (sjdata.sj[0].typeData[0].needleList.length === 1) {
        Message.warning('请至少保留一位路数！')
        return
      }
      sjdata.sj.forEach((o: any, i: number) => {
        o.typeData.forEach((o1: any) => {
          o1.needleList.pop()
        })
      })
    }
    const addRow = (item: any) => {
      // 现有多少行
      let maxRowNumber = 0
      item.typeData.forEach((o: any) => {
        if (o.serialNumber > maxRowNumber) {
          maxRowNumber = o.serialNumber
        }
      })
      let index = sjdata.sj.indexOf(item)
      let n = maxRowNumber - numb.row[index]
      if (n < 0) {
        for (let i = n; i < 0; i++) {
          let nl: any[] = []
          item.typeData[0].needleList.forEach((o: any) => {
            nl.push({
              way: o.way,
              needle: '',
            })
          })
          item.typeData.push({
            serialNumber: maxRowNumber + Math.abs(n - i) + 1,
            needleName: '',
            needleList: nl,
          })
        }
      } else if (n > 0) {
        for (let i = 0; i < n; i++) {
          item.typeData.pop()
        }
      }
    }
    const subRow = (item: any[]) => {
      if (item.length === 1) {
        Message.warning('请最少保留一行！')
        return
      }
      item.pop()
    }
    const searchData = reactive({
      code: '',
      name: '',
    })
    const dataForm = reactive<PSJ>({
      atName: '',
      models: '双面机',
      id: '',
      remark: '',
      firm: '',
      atCode: '',
      arrangement: '',
      deleteState: '',
      obsoleteState: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
    })
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
      // gridOption.value.sizeColumnsToFit();
    }
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          pageData.pageLoading = true
          let sjnulldata = sjhasnull()
          if (sjnulldata !== undefined) {
            Message.error(sjnulldata.type + ':' + sjnulldata.way + '路,未设置，无法保存！')
            pageData.pageLoading = false
            return
          }
          if (pageData.sideTitle === '新增排三角资料') {
            post({
              url: 'product/arrangementTriangle/insert',
              data: {
                // atCode: dataForm.atCode,
                models: dataForm.models,
                atName: dataForm.atName,
                remark: dataForm.remark,
                info: sjdata.sj,
                deleteState: 0,
                obsoleteState: 0,
                loopList:settingLoopData.value
              },
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          } else {
            post({
              url: 'product/arrangementTriangle/update',
              data: {
                id: dataForm.id,
                atName: dataForm.atName,
                models: dataForm.models,
                atCode: dataForm.atCode,
                info: sjdata.sj,
                deleteState: 0,
                obsoleteState: dataForm.obsoleteState,
                remark: dataForm.remark,
                loopList:settingLoopData.value
              },
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (table1Ref.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        draggable: true,
        onOk() {
          pageData.pageLoading = true
          post({
            url: 'product/arrangementTriangle/delete',
            data: table1Ref.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
              } else {
                Message.success({
                  content: '修改失败',
                  duration: 5000,
                })
              }
              doRefresh()
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }
    const sjdata = reactive<{ sj: any[] }>({ sj: [] })

    const editHandler = (record: PSJ) => {
      dataForm.id = record.id
      dataForm.atName = record.atName
      dataForm.obsoleteState = record.obsoleteState
      dataForm.remark = record.remark
      dataForm.arrangement = record.arrangement
      dataForm.models = record.models
      dataForm.atCode = record.atCode
      dataForm.firm = record.firm
      post({ url: 'product/arrangementTriangleInfo/getInfoByAtId?id=' + record.id }).then(
        (result: any) => {
          if (result.code === 200) {
            sjdata.sj = result.data.info
            if (sjdata.sj.length === 1) {
              dataForm.models = '单面机'
            } else {
              dataForm.models = '双面机'
            }
            if (result.data.loopList?.length>0) {
              addFlag.value = 2
              settingLoopData.value = result.data.loopList
            }else{
              addFlag.value = 1
              settingLoopData.value = []
            }
            TempSettingLoopData.value = _.cloneDeep(settingLoopData.value)
            numb.row = result.data.info.map((o: any) => {
              return o.typeData.length
            })
            let maxColNumber = 0
            sjdata.sj[0].typeData[0].needleList.forEach((o: any) => {
              if (o.way > maxColNumber) {
                maxColNumber = parseInt(o.way)
              }
            })
            numb.col = maxColNumber
          }
        }
      )

      pageData.sideTitle = '修改排三角资料'

      pageData.showAdd = true
    }
    const addCancel = () => {
      Object.keys(dataForm).forEach((o) => (dataForm[o] = ''))
      pageData.showAdd = false
    }

    const tagValue = ref<string>(tags[0].id)
    // 设置值
    const setSJValue = (i2: any, item: any) => {
      // item.needle = tagValue.value

      if (item.type == '上盘') {
        if (tagValue.value == '1' || tagValue.value == '3' || tagValue.value == '5') {
          i2.needle = tagValue.value
        } else {
          Message.warning({
            content: '上盘Ո,Ʌ不可选择',
            duration: 5000,
          })
          return
        }
      } else if (item.type == '下盘') {
        if (tagValue.value == '1' || tagValue.value == '2' || tagValue.value == '4') {
          i2.needle = tagValue.value
        } else {
          Message.warning({
            content: '下盘Ս,V不可选择',
            duration: 5000,
          })
          return
        }
      }
    }
    const sm = ref<string>('1')
    watch(
      () => dataForm.models,
      (val, oldValue) => {
        if (val === '单面机') {
          numb.col = 1
          numb.row = [4, 1]

          //单面机
          if (sjdata.sj.length === 2) {
            //切换删上盘
            sjdata.sj.splice(0, 1)
            sjdata.sj[0] = {
              type: '下盘',
              typeData: [
                {
                  serialNumber: 1,
                  needleName: '',
                  needleList: [{ way: 1 }],
                },
                {
                  serialNumber: 2,
                  needleName: '',
                  needleList: [
                    {
                      needle: '',
                      way: 1,
                    },
                  ],
                },
                {
                  serialNumber: 3,
                  needleName: '',
                  needleList: [
                    {
                      needle: '',
                      way: 1,
                    },
                  ],
                },
                {
                  serialNumber: 4,
                  needleName: '',
                  needleList: [
                    {
                      needle: '',
                      way: 1,
                    },
                  ],
                },
              ],
            }
          }
        } else {
          //双面机
          if (sjdata.sj.length === 1) {
            numb.col = 1
            numb.row = [2, 4]
            let maxColNumber = 0
            sjdata.sj[0].typeData[0].needleList.forEach((o: any) => {
              if (o.way > maxColNumber) {
                maxColNumber = parseInt(o.way)
              }
            })
            const list = []
            for (let i = 0; i < maxColNumber; i++) {
              list.push({
                needle: tagValue.value,
                way: 1,
              })
            }
            sjdata.sj.splice(0, 0, {
              type: '上盘',
              typeData: [
                {
                  serialNumber: 1,
                  needleName: '',
                  needleList: [
                    {
                      needle: '',
                      way: 1,
                    },
                  ],
                },
                {
                  serialNumber: 2,
                  needleName: '',
                  needleList: [
                    {
                      needle: '',
                      way: 1,
                    },
                  ],
                },
              ],
            })
            sjdata.sj[1]['typeData'] = []
            sjdata.sj[1]['typeData'].push(
              {
                serialNumber: 1,
                needleName: '',
                needleList: [
                  {
                    needle: '',
                    way: 1,
                  },
                ],
              },
              {
                serialNumber: 2,
                needleName: '',
                needleList: [
                  {
                    needle: '',
                    way: 1,
                  },
                ],
              },
              {
                serialNumber: 3,
                needleName: '',
                needleList: [
                  {
                    needle: '',
                    way: 1,
                  },
                ],
              },
              {
                serialNumber: 4,
                needleName: '',
                needleList: [
                  {
                    needle: '',
                    way: 1,
                  },
                ],
              }
            )
          }
        }
      }
    )
    const sjhasnull = (): { way: number; type: string } | undefined => {
      let d: { way: number; type: string } | undefined = undefined

      sjdata.sj.forEach((o) => {
        o.typeData.forEach((o1: any) => {
          o1.needleList.forEach((o2: any) => {
            if (o2.needle == '' || o2.needle === undefined || o2.needle == null) {
              d = { way: o2.way, type: o.type }
              return false
            }
          })
        })
      })
      return d
    }
    const okloading = ref<boolean>(false)
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const localeText1: any = ref(localeText)
    const huiche = () => {
      page.value = 1
      cxbl = searchData.name
      doRefresh()
    }

    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('typsj.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('typsj.xz')) {
      pageData.btnList.push('新增')
    }
    if (permissionStore.hasPermisson('typsj.sc')) {
      pageData.btnList.push('删除')
    }
    if (permissionStore.hasPermisson('typsj.xg')) {
      pageData.isEdit = true
    }
    const pagingList1: any = ref(pagingList)

    const psjpblist = ref<any[]>([])
    const psjpblistSelect = (v: any) => {
      post({
        url: 'purchase/MaterialInfo/getFieldValue',
        data: {
          "auditState": 1,
          materialName: v
        },
      }).then(({ code, data }) => {
        if (code === 200) {
          psjpblist.value = data
        }
      })
    }
    return {
      colState,
      psjpblistSelect,
      psjpblist,
      permissionStore,
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      okloading,
      sm,
      tagValue,
      setSJValue,
      numb,
      subRow,
      addRow,
      subCol,
      addCol,
      sjdata,
      addCancel,
      searchData,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      addsonlist,
      selChange,
      headerShow,
      tags,
      handleChange,
      gridReady,
      table1Ref,
      configTable1,
      settingLoopVisible,
      setLoop,
      settingLoopOK,
      settingLoopColumns,
      settingLoopData,
      settingLoopKeys,
      settingLoopCheckBox,
      wayEndChange,
      loopCountChange,
      loopAdd,
      loopDel,
      countLoopBetween,
      addFlag,
      TempSettingLoopData
    }
  },
  components: { Toolbar, Scrollbar,  },
}
</script>
<style scoped lang="less">
.thead {
  white-space: nowrap;
  justify-content: center;

  .th {
    padding: 5px;
    box-sizing: border-box;
    text-align: center;
    display: inline-block;
  }

  width: 100%;
  text-align: left;
}

.tbody {
  margin: 10px auto;
  white-space: nowrap;
  justify-content: center;

  .td {
    text-align: center;
    padding: 5px;
    box-sizing: border-box;
    display: inline-block;
  }

  text-align: left;
}
.opcity-ipt{
    opacity: 0.5;
}
</style>